<?php
/**
 * Created by PhpStorm.
 * User: wyq
 * Date: 2021/8/3
 * Time: 10:41
 */

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Database\Capsule\Manager as Db;

class ApiController extends AppController
{
    public $uses = array('Article');
    public $components = array('publicFunction');


    public function __construct(CakeRequest $request = null, CakeResponse $response = null)
    {
        parent::__construct($request, $response);
        //允许的源域名
        header("Access-Control-Allow-Origin: *");
        //允许的请求头信息
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        //允许的请求类型
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
    }

    /*
     * 展示信息 get请求
     */
    public function index()
    {
        $data = $this->Article->findAll();
        foreach ($data as $k => $v) {
            $res[$k]['id'] = $v['Article']['id'];
            $res[$k]['title'] = $v['Article']['title'];
        }
        $this->publicFunction->success($res);
    }

    /*
     * 展示一条信息 get请求
     */
    public function view($id)
    {
        $data = $this->Article->findOne($id);
        $res = $data['Article'];
        $this->publicFunction->success($res);
    }

    /*
     * 新增一条信息 Post请求
     */
    public function add()
    {
        $post = file_get_contents('php://input');
        $data = json_decode($post, true);
        $res = $this->Article->dell($data);
        $this->publicFunction->success($res['Article']);
    }

    /*
     * 修改页面展示 Put请求
     */
    public function edit($id)
    {
        $post = file_get_contents('php://input');
        $data = json_decode($post, true);
        if ($data) {
            $data['id'] = $id;
            $data = $this->Article->dell($data);
            $res = $data['Article'];
            $this->publicFunction->success($res);
        } else {
            $data = $this->Article->findOne($id);
            $res = $data['Article'];
            $this->publicFunction->success($res);
        }
    }

    /*
     * 删除页面处理 delete请求
     */
    public function delete($id)
    {
        $data = $this->Article->del($id);
        if ($data) {
            $this->publicFunction->success();
        } else {
            $this->publicFunction->error();
        }
    }

    //去支付逻辑
    public function pay()
    {
        $request = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
        $data = $this->publicFunction->filterParams($request);
        $orderId = "PAY".time().rand(1000000,10000000);
        $subject = "金币";
        $amount = rand(0.1,100);
        $body = "买了不会发货";
        switch ($data['pay_type']) {
            case "wechet":
                break;
            case "alipay":
            default :
            echo "<form id='alipayment' action='/alipay/pagepay/pagepay.php' method='post' style='display: none;'>
            <input id='WIDout_trade_no' name='WIDout_trade_no' value=$orderId/>
            <input id='WIDsubject' name='WIDsubject' value=$subject/>
            <input id='WIDtotal_amount' name='WIDtotal_amount' value=$amount />
            <input id='WIDbody' name='WIDbody' value=$body/>
            </form><script>document.getElementById('alipayment').submit();</script>";
            break;
        }
        die;
    }

    //支付同步
    public function alipayCallback()
    {
        $request = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
        $data = $this->publicFunction->filterParams($request);
        $config = "";//无用
        require_once("./alipay/config.php");
        require_once './alipay/pagepay/service/AlipayTradeService.php';
        $alipaySevice = new \AlipayTradeService($config);
        var_dump($data);die;
        $result = $alipaySevice->check($data);
        if ($result) {
            echo "支付成功";
        } else {
            echo "支付失败";
        }
        die;
    }

    //支付宝异步回调
    public function aliPayNotify()
    {
        $request = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
        $data = $this->publicFunction->filterParams($request);
        $config = "";//无用
        $this->log('url:\api\aliPayNotify | aliPayNotify-params:'.json_encode($data),LOG_INFO);
        require_once("./alipay/config.php");
        require_once './alipay/pagepay/service/AlipayTradeService.php';
        $alipaySevice = new \AlipayTradeService($config);
        $result = $alipaySevice->check($data);
        //验签失败
        if (!$result){
            $this->log('url:\api\aliPayNotify | aliPayNotify-error:验签失败'.json_encode($data),LOG_ERR);
            echo "fail";die;
        }
        //商户订单号
        $out_trade_no = $data['out_trade_no'];
        //交易总金额
        $total_amount = $data['total_amount'];
        //交易状态
        $trade_status = $data['trade_status'];
        if ($trade_status == "TRADE_FINISHED"){
            $this->log('url:\api\aliPayNotify | aliPayNotify-success',LOG_INFO);
            echo "success";die;
        }
        //对订单做判断
        //订单号是否存在数据库中查看
        $order_id = "PAY16443728188675342";//test
        //总交易金额，数据库中查看
        $amount = 100;//test
        if ($total_amount != $amount) {
            $this->log('url:\api\aliPayNotify | aliPayNotify-error:订单金额与支付金额不符',LOG_ERR);
            //订单金额与支付金额不符
            echo "fail";die;
        }
        if (!$order_id){
            //订单不存在
            $this->log('url:\api\aliPayNotify | aliPayNotify-error:订单不存在',LOG_ERR);
            echo  "fail";die;
        }
        //支付成功逻辑处理代码,对订单以及其他逻辑进行修改

        //记录支付宝交易到日志记录表中，需要记录支付宝的支付编号，以及此次支付宝传递过来的参数。


        $this->log('url:\api\aliPayNotify | aliPayNotify-success',LOG_INFO);
        echo "success";die;
    }



    //验签流程

    //获取签名
    public function getSign($params)
    {
        if (!empty($params)) {
            //验证签名时传递的参数会多两个将哪两个参数去掉，不然验证会失败
            if (isset($params['sign']) || isset($params['sign_type'])) {
                unset($params['sign']);
                unset($params['sign_type']);
            }
            //现将数组进行排序，使用ksort改变数组的顺序，保证同样的数组不会出现其他排列顺序
            ksort($params);
            $signStr = "";
            foreach ($params as $k => $v){
                //$v为空不做加密处理
                if (empty($v)){
                    continue;
                }
                //避免最后多一个&符号
                if ($k == 0){
                    $signStr .= $k.'='.$v;
                }else{
                    $signStr .= '&'.$k.'='.$v;
                }
            }
            //加密签名操作
            $sign = $this->publicFunction->encrypt($signStr);
            $res = [
                'sign' => $sign,
                'sign_type' => "encrypt"
            ];
            return $res;
        }
        return false;
    }

    //验证签名
    public function checkSign($params)
    {
        $newSign = $this->getSign($params);
        if ($newSign['sign'] == $params['sign']) {
            return true;
        }
        return false;
    }


    //发送请求
    public function send()
    {
        $data = [
            'out_trade_no' => '213123123123123123',
            'total_amount' => '100.00',
            'time' => time(),
        ];
        $sign = $this->getSign($data);
        $data['sign'] = $sign['sign'];
        $data['sign_type'] = $sign['sign_type'];
        $url = "http://cakephp.com/api/notify";
        //请求
        $res = $this->publicFunction->curlRequest($url, true, $data);
        var_dump($res);die;
    }

    public function notify()
    {
        //参数获取
        $request = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
        $data = $this->publicFunction->filterParams($request);
        //参数验证
        $res = $this->checkSign($data);
        if ($res){
            echo  "验证成功";die;
        }else{
            echo "验证失败";die;
        }
    }


    public function code()
    {

        $url = Router::url(array(
            'controller' => 'api',
            'action' => 'code',
            '?' => ['id'=>rand(1,20)],
        ));
        $url = "http://cakephp.com".$url;
        $code = new \Endroid\QrCode\QrCode($url);
//        header('Content-Type: '.$result->getMimeType());
        $writer = new PngWriter();
        $result = $writer->write($code);
        header('Content-Type: '.$result->getMimeType());
        echo $result->getString();die;
    }
    
    public function test()
    {
       $res = Db::table('users')->get();
        var_dump($res);die;
    }
}